import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '../router'
const service = axios.create({
  // headers: { 'Content-Type': 'application/json' },
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()
  }
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  // console.log(response)
  const res = response.data
  // 响应
  if (res.code === 401) {
    MessageBox.confirm(res.msg, {
      confirmButtonText: '去登入',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      router.push(`/login?redirect=${router.currentRoute.fullPath}`)
    })
  }
  if (res.code !== 200) {
    Message({
      message: res.msg || 'Error',
      type: 'error',
      duration: 5 * 1000
    })

    // token的code
    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
        confirmButtonText: '重新登入',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          // 刷新浏览器
          location.reload()
        })
      })
    }
    return Promise.reject(res.msg || 'Error')
  } else {
    return res
  }
},
error => {
  // console.log(error)
  Message({
    message: error.msg,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
